<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from "@/utils/axios.js";
import CommentCard from '@/components/CommentCard.vue';

const route = useRoute();
const router = useRouter();

// 获取帖子ID
const postId = ref(route.params.id || '');

// 响应式状态
const post = ref({

});
const isLoading = ref(true);
const commentContent = ref('');
const isSubmitting = ref(false);
const showCommentDialog = ref(false);

// 评论分页相关
const page = ref(1);
const limit = ref(6);


// 获取帖子详情
const fetchPostDetail = async () => {
  // 如果postId无效，不发送请求
  if (!postId.value || postId.value === 'undefined') {
    console.warn("帖子ID无效，无法获取帖子详情");
    isLoading.value = false;
    return;
  }

  try {
    isLoading.value = true;

    const res = await axios.post("/api/postDetail/getDetail",postId.value);
    console.log(res)
    if (res.code === 200) {
      post.value = res.data;
      // 获取评论
      // fetchComments();
    } else {
      console.error("获取帖子详情失败:", res.message);
    }
  } catch (error) {
    console.error("获取帖子详情失败:", error);
  } finally {
    isLoading.value = false;
  }
};

onMounted(()=>{
  console.log("初始化")
  fetchPostDetail();
})
// 获取评论列表
const fetchComments = async (isLoadMore = false) => {
  if (!postId.value || postId.value === 'undefined') {
    console.warn("帖子ID无效，无法获取评论");
    return;
  }

  try {

    // 请求参数
    const params = {
      page: ++page.value,
      limit: limit.value
    };

    const res = await axios.post(`/api/postDetail/getMoreComm/${postId.value}`, { params });
    if (res.code === 200) {
      const newComments = res.data || [];
      // 如果是加载更多，合并评论列表
      if (isLoadMore) {
        post.value.comments = [...post.value.comments, ...newComments];
        console.log("加载更多评论:", post.value.comments);
      }

    } else {
      console.error("获取评论失败:", res.message);
    }
  } catch (error) {
    console.error("获取评论失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 加载更多评论
const loadMoreComments = () => {
  if((limit.value*page.value)>post.value.commentCount){return}

    fetchComments(true);

};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    alert("评论内容不能为空");
    return;
  }

  try {
    isSubmitting.value = true;

    // 检查是否是回复评论
    let replyToUserId = null;
    let actualContent = commentContent.value;

    // 如果评论内容以@开头，说明是回复评论
    if (commentContent.value.startsWith('@')) {
      // 提取用户名
      const atIndex = commentContent.value.indexOf(' ');
      if (atIndex !== -1) {
        const username = commentContent.value.substring(1, atIndex);
        actualContent = commentContent.value.substring(atIndex + 1).trim();

        // 在评论列表中查找该用户
        const targetComment = comments.value.find(comment =>
          comment.user && comment.user.nickname === username
        );

        if (targetComment) {
          replyToUserId = targetComment.user.id;
        }
      }
    }

    const res = await axios.post(`/api/comment/add`, {
      postId: postId.value,
      content: actualContent,
      replyToUserId: replyToUserId
    });

    if (res.code === 200) {
      // 评论成功，清空输入框并刷新评论列表
      commentContent.value = '';
      fetchComments();
      // 更新帖子评论数
      post.value.commentCount = (post.value.commentCount || 0) + 1;
    } else {
      alert(res.message || "评论失败");
    }
  } catch (error) {
    console.error("提交评论失败:", error);
    alert("提交评论失败，请稍后重试");
  } finally {
    isSubmitting.value = false;
  }
};

// 点赞帖子
const likePost = async () => {
  if (!postId.value || postId.value === 'undefined') {
    alert("帖子ID无效，无法点赞");
    return;
  }

  try {
    const res = await axios.post(`/api/post/like/${postId.value}`);
    if (res.code === 200) {
      // 更新点赞状态和数量
      post.value.isLiked = !post.value.isLiked;
      post.value.likeCount = post.value.isLiked ?
        (post.value.likeCount || 0) + 1 :
        (post.value.likeCount || 0) - 1;
    } else {
      alert(res.message || "操作失败");
    }
  } catch (error) {
    console.error("点赞失败:", error);
    alert("操作失败，请稍后重试");
  }
};

// 收藏帖子
const bookmarkPost = async () => {
  if (!postId.value || postId.value === 'undefined') {
    alert("帖子ID无效，无法收藏");
    return;
  }
  try {
    const res = await axios.post(`/api/post/bookmark/${postId.value}`);
    if (res.code === 200) {
      // 更新收藏状态
      post.value.isBookmarked = !post.value.isBookmarked;
    } else {
      alert(res.message || "操作失败");
    }
  } catch (error) {
    console.error("收藏失败:", error);
    alert("操作失败，请稍后重试");
  }
};

// 格式化发布时间
const formatPostTime = (publishTime) => {
  // 如果publishTime不存在，返回空字符串
  if (!publishTime) {
    return '';
  }

  // 如果publishTime是字符串，转换为Date对象
  const publishDate = typeof publishTime === 'string' ? new Date(publishTime) : publishTime;

  // 如果publishDate不是有效的Date对象，返回空字符串
  if (isNaN(publishDate.getTime())) {
    return '';
  }

  const now = new Date();
  const diffTime = Math.abs(now - publishDate);
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
  const diffMonths = Math.floor(diffDays / 30);
  const diffYears = Math.floor(diffDays / 365);

  // 获取星期几
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekday = weekdays[publishDate.getDay()];

  // 获取月份和日期
  const month = publishDate.getMonth() + 1;
  const day = publishDate.getDate();
  const year = publishDate.getFullYear();

  if (diffHours < 1) {
    return '刚刚';
  } else if (diffHours < 24) {
    return `${diffHours}小时前`;
  } else if (diffDays < 7) {
    return `${diffDays}天前发布`;
  } else if (diffDays < 30) {
    return `${weekday}`;
  } else if (diffMonths < 12) {
    return `${month}月${day}日发布`;
  } else {
    return `${year}年${month}月${day}日发布`;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 提交评论并关闭对话框
const submitCommentAndClose = async () => {
  await submitComment();
  if (!isSubmitting.value) {
    showCommentDialog.value = false;
    commentContent.value = '';
  }
};

// 关注/取消关注用户
const toggleFollow = () => {
  data.user.isFollowing = !data.user.isFollowing;
  data.user.followerCount += data.user.isFollowing ? 1 : -1;
  // 实际项目中这里需要调用接口
  showToast(data.user.isFollowing ? "关注成功" : "已取消关注");
};
</script>

<template>
  <div class="post-detail-container">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="nav-left">
        <div class="back-button" @click="goBack">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="15 18 9 12 15 6"></polyline>
          </svg>
        </div>
        <div class="page-title">帖子详情</div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 帖子内容 -->
    <div v-else class="post-content">
      <!-- 作者信息 -->
      <div class="author-section" style="display: flex;">
        <router-link  :to="`/user/${post.userId}`" class="author-info">
        <div class="author-info">
          <img :src="post.user?.avatar||'/userTx.svg'" class="author-avatar">
          <div class="author-meta">
            <p class="author-name">{{ post.user?.nickname }}</p>
            <div class="meta-info">
              <span class="rank-badge" :class="`rank-${post.user?.level || 1}`">
                Lv.{{ post.user?.level || 1 }}
              </span>
              <span class="post-time">{{ formatPostTime(post.publishTime) }}</span>
            </div>
          </div>
        </div>
        </router-link>

        <div class="follow-section">
          <button
              class="follow-button"
              :class="{ 'following': false }"
              @click="toggleFollow"
          >
            {{ false ? "已关注" : "关注" }}
          </button>
        </div>
      </div>

      <!-- 帖子标题和内容 -->
      <div class="post-body">
        <h1 class="post-title">{{ post.title }}</h1>
        <div class="post-text">{{ post.content }}</div>
      </div>

      <!-- 帖子图片 -->
      <div v-if="post.postImages && post.postImages.length > 0" class="post-images">
        <div
          v-for="(image, index) in post.postImages"
          :key="index"
          class="image-container"
        >
          <img :src="image.imageUrl" :alt="`${post.title} ${index + 1}`" class="post-image">
        </div>
      </div>

      <!-- 话题标签 -->
      <div v-if="post.tags && post.tags.length > 0" class="tags-container">
        <span
          v-for="(tag, index) in post.tags"
          :key="index"
          class="topic-tag"
          :class="`tag-${tag.type}`"
        >
          {{ tag.text }}
        </span>
      </div>
    </div>

    <!-- 评论区 -->
    <div v-if="!isLoading" class="comments-section">
      <h2 class="comments-title">评论 ({{ post.commentCount}})</h2>

      <!-- 评论列表 -->
      <div v-if="post.commentCount > 0" class="comments-list">
        <CommentCard
          v-for="comment in post.comments"
          :key="comment.commentId"
          :comment="comment"
        />
      </div>

      <!-- 无评论提示 -->
      <div v-else class="no-comments">
        暂无评论，来发表第一条评论吧！
      </div>
      <div v-if="post.commentCount > 0">
        <div v-if="post.comments.length<post.commentCount" class="load-more" @click="loadMoreComments()">加载更多</div>
        <div v-else class="load-more">没有更多了</div>
      </div>

    </div>
    <!-- 评论对话框 -->
    <van-dialog v-model:show="showCommentDialog" title="发表评论" :show-confirm-button="false" class="comment-dialog">
      <div class="comment-dialog-content">
        <textarea
          v-model="commentContent"
          class="comment-textarea"
          placeholder="写下你的评论..."
          rows="4"
          autofocus
        ></textarea>
        <div class="dialog-buttons">
          <button class="cancel-button" @click="showCommentDialog = false">取消</button>
          <button class="submit-button" @click="submitCommentAndClose" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '发表' }}
          </button>
        </div>
      </div>
    </van-dialog>

    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <div class="comment-input-wrapper" @click="showCommentDialog = true">
        <div class="comment-input-placeholder">
          <img src="/chat-o.svg" alt="评论" class="icon-svg">
          <span>说点什么...</span>
        </div>
      </div>
      <div class="action-buttons">
        <div class="action-button" :class="{ active: post.isLiked }" @click="likePost">
          <img src="/good-job.svg" alt="点赞" class="icon-svg" :class="{ 'icon-liked': post.isLiked }">
          <span>{{ post.isLiked ? (post.likeCount || 0) + 1 : (post.likeCount || 0) }}</span>
        </div>
        <div class="action-button" @click="showCommentDialog = true">
          <img src="/chat-o.svg" alt="评论" class="icon-svg">
          <span>{{ post.commentCount || 0 }}</span>
        </div>
        <div class="action-button" :class="{ active: post.isBookmarked }" @click="bookmarkPost">
          <i :class="post.isBookmarked ? 'fa fa-bookmark' : 'fa fa-bookmark-o'">收藏</i>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 容器样式 */
.post-detail-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f9f9f9;
  z-index: 1000;
  overflow-y: auto;
  height: 100vh;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  height: 56px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.nav-left {
  display: flex;
  align-items: center;
}

.back-button {
  width: 24px;
  height: 24px;
  margin-right: 16px;
  cursor: pointer;
  color: #333;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  margin-top: 56px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #1890ff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 帖子内容样式 */
.post-content {
  margin-top: 56px;
  background-color: #fff;
  padding: 16px;
}

/* 作者信息样式 */
.author-section {
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.author-meta {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.meta-info {
  display: flex;
  align-items: center;
  margin-top: 4px;
}

.rank-badge {
  margin-right: 8px;
  font-size: 12px;
  font-weight: 500;
  padding: 2px 6px;
  border-radius: 4px;
  color: white;
}

.rank-1 { background-color: #9CA3AF; }
.rank-2 { background-color: #10B981; }
.rank-3 { background-color: #3B82F6; }
.rank-4 { background-color: #8B5CF6; }
.rank-5 { background-color: #F59E0B; }

.post-time {
  font-size: 12px;
  color: #999;
}

/* 帖子正文样式 */
.post-body {
  margin-bottom: 16px;
}

.post-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin: 0 0 12px 0;
}

.post-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

/* 帖子图片样式 */
.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.image-container {
  width: calc(33.333% - 6px);
  aspect-ratio: 1/1;
  overflow: hidden;
  border-radius: 8px;
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 话题标签样式 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.topic-tag {
  font-size: 12px;
  font-weight: 500;
  padding: 4px 10px;
  border-radius: 16px;
}

.tag-blue { background-color: #EFF6FF; color: #2563EB; }
.tag-purple { background-color: #F9FAFF; color: #7C3AED; }
.tag-green { background-color: #ECFDF5; color: #059669; }
.tag-pink { background-color: #FDF2F8; color: #DB2777; }

/* 互动按钮样式 */
.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.2s;
}

.action-button:hover {
  background-color: #f5f5f5;
}

.action-button.active {
  color: #1890ff;
}

.icon-svg {
  width: 20px;
  height: 20px;
}

.icon-liked {
  filter: invert(16%) sepia(99%) saturate(7459%) hue-rotate(358deg) brightness(96%) contrast(112%);
}

/* 评论区样式 */
.comments-section {
  margin-top: 12px;
  background-color: #fff;
  padding: 16px;
}

.comments-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

/* 评论输入框样式 */
.comment-input-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.comment-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  font-size: 14px;
  resize: none;
  margin-bottom: 12px;
  box-sizing: border-box;
  transition: all 0.3s;
  min-height: 60px;
  font-family: inherit;
}

.comment-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.submit-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  float: right;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.submit-button:hover {
  background-color: #40a9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.submit-button:active {
  transform: translateY(0);
}

.submit-button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 评论列表样式 */
.comments-list {
  margin-top: 20px;
}

/* 无评论提示样式 */
.no-comments {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

/* 底部固定互动区域样式 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1001; /* 确保在内容之上 */
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
}

.bottom-actions .comment-input-container {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.bottom-actions .comment-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  resize: none;
  margin-right: 12px;
  max-height: 80px;
  background-color: #f8f8f8;
  transition: all 0.3s;
}

.bottom-actions .comment-input:focus {
  outline: none;
  border-color: #1890ff;
  background-color: #fff;
}

.bottom-actions .submit-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 18px;
  padding: 8px 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: background-color 0.3s;
}

.bottom-actions .submit-button:hover {
  background-color: #40a9ff;
}

.bottom-actions .submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.bottom-actions .post-actions {
  display: flex;
  justify-content: space-around;
  padding: 8px 0 0 0;
  border-top: none;
}

.bottom-actions .action-button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  padding: 8px 0;
  transition: all 0.2s;
}

.bottom-actions .action-button:hover {
  background-color: transparent;
}

.bottom-actions .action-button.active {
  color: #1890ff;
}

.bottom-actions .icon-svg {
  width: 22px;
  height: 22px;
}

/* 调整内容区域，为底部固定区域留出空间 */
.post-content, .comments-section {
  margin-bottom: 100px; /* 根据底部固定区域的高度调整 */
}

/* 底部操作栏布局样式 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1001;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  height: 60px;
}

.comment-input-wrapper {
  flex: 1;
  height: 36px;
  background-color: #f5f5f5;
  border-radius: 18px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  margin-right: 12px;
  cursor: pointer;
}

.comment-input-placeholder {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  width: 50%;
}

.action-buttons .action-button {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  padding: 8px 0;
  transition: all 0.2s;
}

.action-buttons .action-button:hover {
  background-color: transparent;
}

.action-buttons .action-button.active {
  color: #1890ff;
}

.action-buttons .icon-svg {
  width: 22px;
  height: 22px;
}

/* 评论对话框按钮样式 */
.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  padding: 12px 16px 0;
  gap: 12px;
}

.cancel-button {
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 18px;
  padding: 8px 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-button:hover {
  background-color: #e8e8e8;
}

.submit-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 18px;
  padding: 8px 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-button:hover {
  background-color: #40a9ff;
}

.submit-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 加载更多样式 */
.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 16px 0;
  padding: 10px 0;
  position: relative;
  color: #666;
  font-size: 14px;
}

.load-more::before,
.load-more::after {
  content: "";
  flex: 1;
  height: 1px;
  background: linear-gradient(to right, transparent, #e0e0e0, transparent);
  margin: 0 15px;
}

.load-more:hover {
  color: #1890ff;
  cursor: pointer;
  transition: color 0.3s ease;
}
.follow-section {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.follow-button {
  padding: 6px 16px;
  border-radius: 20px;
  background-color: #1989fa;
  color: white;
  border: none;
  font-size: 14px;
  cursor: pointer;
}

.follow-button.following {
  background-color: #f0f0f0;
  color: #333;
}
</style>
